<template>
  <div class="form">
    <a-spin tip="Loading..." :spinning="loading">
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-model-item label="投票主题：" prop="subject">
          <a-input
            v-model.trim="form.subject"
            placeholder="请输入投票主题"
            :maxLength="50"
          >
          </a-input>
        </a-form-model-item>
        <a-row>
          <a-col :offset="labelCol.span">
            <span class="pwd-tip">上限50个字</span>
          </a-col>
        </a-row>

        <a-form-model-item label="活动图片：" prop="image">
          <UploadImg
            :disabled="false"
            :images="form.images"
            v-model="form.images"
          ></UploadImg>
        </a-form-model-item>
        <a-row>
          <a-col :offset="labelCol.span">
            <span class="pwd-tip"
              >上限1张，分辨率 630*354px，支持 jpg、png 格式</span
            >
          </a-col>
        </a-row>
        <a-form-model-item label="主题描述：" prop="content">
          <Editor
            ref="editor"
            :content="form.content"
            :maxLength="1000"
            placeholder="请输入主题描述"
          />
        </a-form-model-item>
        <a-row>
          <a-col :offset="labelCol.span">
            <span class="pwd-tip">上限1000个字</span>
          </a-col>
        </a-row>

        <a-form-model-item label="推送范围：" prop="sendRange">
          <a-row>
            <a-col :span="6">
              <a-radio-group v-model="form.sendRange">
                <a-radio :value="1">小区</a-radio>
                <a-radio :value="2">小区楼宇</a-radio>
              </a-radio-group>
            </a-col>
            <a-col :span="8">
              <a-select
                v-model="form.spaceId"
                :placeholder="
                  form.sendRange === 1 ? '请选择小区' : '请选择小区楼宇'
                "
              >
                <a-select-option
                  v-for="(node, index) in spaceList"
                  :key="index"
                  :value="node.value"
                  >{{ node.name }}</a-select-option
                >
              </a-select>
            </a-col>
            <a-col :span="9" :offset="1">目标户数：XXX 已认证：XXX </a-col>
          </a-row>
        </a-form-model-item>

        <a-form-model-item label="上限人数：" prop="maxType">
          <a-row>
            <a-col :span="6">
              <a-radio-group v-model="form.maxType">
                <a-radio :value="1">不限</a-radio>
                <a-radio :value="2">限制人数</a-radio>
              </a-radio-group>
            </a-col>
            <a-col :span="8" v-show="form.maxType === 2">
              <a-input-number
                v-model="form.count"
                placeholder="请输入限制人数"
                :min="1"
            /></a-col>
          </a-row>
        </a-form-model-item>

        <a-form-model-item label="截止日期：" prop="endTime">
          <a-date-picker v-model="form.endTime" />
        </a-form-model-item>
        <a-form-model-item label="投票类型：" prop="voteUpdateType">
          <a-radio-group v-model="form.voteUpdateType">
            <a-radio :value="1">提交后不可修改</a-radio>
            <a-radio :value="2">截止日期前可修改</a-radio>
          </a-radio-group>
        </a-form-model-item>

        <a-form-model-item label="选项类型：" prop="selectType">
          <a-radio-group v-model="form.selectType">
            <a-radio :value="1">单选</a-radio>
            <a-radio :value="2">多选</a-radio>
          </a-radio-group>
        </a-form-model-item>

        <a-form-model-item label="投票结果：" prop="voteResult">
          <a-radio-group v-model="form.voteResult">
            <a-radio :value="1">显示</a-radio>
            <a-radio :value="2">隐藏</a-radio>
          </a-radio-group>
        </a-form-model-item>

        <a-form-model-item label="选项：" prop="voteOptionList">
          <div class="list-tip">
            <span class="pwd-tip">至少2个选项，选项内容上限100个字</span>
            <div class="list-count">
              <span class="text list-len">{{
                form.voteOptionList && form.voteOptionList.length
              }}</span>
              <span class="text list-total">/{{ maxCount }}</span>
            </div>
          </div>
          <SelectList :list="form.voteOptionList"></SelectList>
        </a-form-model-item>
      </a-form-model>
    </a-spin>
  </div>
</template>

<script>
import Editor from "@/components/Editor";
import UploadImg from "@/components/UploadImg";
import SelectList from "./SelectList";
import { guid, formateByRegx } from "@/utils";
import httpApi from "@/api/vote";

export default {
  components: {
    Editor,
    UploadImg,
    SelectList
  },
  data() {
    let checkMax = (rule, value, callback) => {
      if (value === 2 && !this.form.count) {
        callback(new Error("请输入上限人数"));
      } else {
        callback();
      }
    };

    let checkListCtn = (rule, value, callback) => {
      if (value.length) {
        if (value.length < 2) {
          callback(new Error("至少2个选项"));
        } else {
          let pass = value.some((v) => !v.optionContent);
          if (pass) {
            callback(new Error("请输入选项描述文字"));
          } else {
            callback();
          }
        }
      } else {
        callback(new Error("至少2个选项"));
      }
    };
    return {
      maxCount: 30, //最大选项卡个数
      newList: [], //排序后新数据
      loading: false,
      labelCol: { span: 4 },
      wrapperCol: { span: 10 },
      form: {},
      rules: {
        subject: [
          { required: true, message: "请输入投票主题", trigger: "change" }
        ],
        images: [{ required: false }],
        content: [{ required: false }],
        maxType: [{ required: true, validator: checkMax, trigger: "change" }],
        sendRange: [
          { required: true, message: "请选择推送范围", trigger: "change" }
        ],
        endTime: [
          { required: true, message: "请选择截止日期", trigger: "change" }
        ],
        voteUpdateType: [
          { required: true, message: "请选择投票类型", trigger: "change" }
        ],
        selectType: [
          { required: true, message: "请选择选项类型", trigger: "change" }
        ],
        voteResult: [
          { required: true, message: "请选择投票结果", trigger: "change" }
        ],
        voteOptionList: [
          { required: true, validator: checkListCtn, trigger: "change" }
        ]
      }
    };
  },
  props: {
    data: {
      type: Object,
      default: () => ({}),
      required: true
    },
    type: {
      type: String,
      default: "",
      required: true
    }
  },
  watch: {
    data: {
      immediate: true,
      handler(value) {
        this.form = Object.assign({}, value);
      }
    }
  },
  provide() {
    return {
      handleAddList: this.handleAddList,
      removeList: this.removeList,
      handleSortList: this.handleSortList
    };
  },
  computed: {
    operName() {
      return this.type === "add" ? "新增" : "编辑";
    },
    spaceList() {
      // 1 小区  2 小区楼宇
      return this.form.sendRange === 1 ? [] : [];
    }
  },
  methods: {
    onChangeTime(val) {
      this.form.endTime = (val && val.format("YYYY-MM-DD")) || undefined;
    },
    validate() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let data = { ...this.form };
          if (this.newList.length) {
            data.voteOptionList = this.newList;
          }
          data.content = formateByRegx(this.$refs.editor.getContent() || "");
          console.log("--------富文本内容:--------", data.content);
          data.endTime = data.endTime.format("YYYY-MM-DD");
          this.uploadFace(data);
        } else {
          return false;
        }
      });
    },
    uploadFace(data) {
      this.loading = true;
      let voteOptionList = [];
      let picFileId = this.form.images.length && this.form.images[0].picFileId;
      data.voteOptionList.forEach((element, index) => {
        let node = { ...element };
        delete node.index; //delete index
        node.sort = index;
        voteOptionList.push(node);
      });
      let query = {
        content: data.content,
        contentId: data.contentId || undefined,
        endTime: data.endTime,
        isRealName: 2, //是否实名 1是 2 否
        maxUserNum: data.maxType === 1 ? undefined : data.count,
        selectType: data.selectType,
        subject: data.subject,
        voteUpdateType: data.voteUpdateType,
        picFileId: picFileId || undefined,
        voteOptionList
      };
      httpApi
        .save(query)
        .then((res) => {
          this.loading = false;
          if (res.retcode === 0) {
            this.$message.success(`${this.operName}成功！`);
            this.$router.back();
          } else {
            this.$message.error(`${this.operName}失败！`);
          }
        })
        .catch((err) => {
          this.loading = false;
          this.$message.error(err.msg || `${this.operName}失败！`);
        });
    },
    handleAddList() {
      // 添加
      if (this.form.voteOptionList.length === this.maxCount) {
        return;
      }
      this.form.voteOptionList.push({
        index: guid(),
        optionContent: ""
      });
    },
    handleSortList(list) {
      // 排序
      this.newList = list;
    },
    removeList(item) {
      // 删除
      let index = -1;
      this.form.voteOptionList.some((node, indx) => {
        // 自己添加index  接口返回id
        if (item.id && item.id === node.id) {
          index = indx;
          return true;
        } else if (item.index && item.index === node.index) {
          index = indx;
          return true;
        } else {
          return false;
        }
      });
      this.form.voteOptionList.splice(index, 1);
    }
  }
};
</script>

<style lang="less" scoped>
.form {
  background-color: #ffff;
  border-radius: 8px;
  padding: 38px;

  .ant-form {
    .pwd-tip {
      height: 34px;
      display: inline-block;
      .font-Medium(12px,rgba(0, 0, 0, 0.45),18px,400);
    }

    .list-tip {
      display: flex;
      flex-flow: row nowrap;
      align-items: center;
      justify-content: space-between;
      .pwd-tip {
        line-height: 34px;
      }
      .list-count {
        .text {
          font-size: 12px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
        }
        .list-len {
          color: #1890ff;
        }
        .list-total {
          color: #999;
        }
      }
    }
  }
}
</style>
